#!/usr/bin/env python2.7

# bender.py

import os, sys
#import re
#from datetime import datetime, timedelta
#from dateutil.parser import parse
import numpy as np
import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure

#from mpl_toolkits.basemap import Basemap
#from matplotlib import mlab
#from netCDF4 import Dataset
from PySide.QtCore import *
from PySide.QtGui import *
from ui_itemlist import *
from metlib.data.boundary import Limiter

class Itemlist(QWidget, Ui_ItemlistWidget):
    rowChanged = Signal(int)

    def __init__(self, parent=None, itemnames=['a', 'b', 'c'], itemrecs=[]):
        super(Itemlist, self).__init__(parent)
        self.setupUi(self)
        self.parent = parent
        
        self.L = Limiter(0, 0)
        self.itemd = dict()
        self.itemnames = []
        self.itemrecs = []
        if itemnames:
            self.load(itemnames, itemrecs)

        self.prevButton.clicked.connect(self.prevrow)
        self.nextButton.clicked.connect(self.nextrow)
        self.listWidget.currentRowChanged.connect(self.on_rowChange)

    def load(self, itemnames, itemrecs=[]):
        self.listWidget.clear()
        self.listWidget.addItems(itemnames)
        if self.index != 0:
            self.index = 0
        self.itemnames = itemnames
        self.L = Limiter(0, len(itemnames)-1)
        if itemrecs:
            self.itemrecs = itemrecs
            self.itemd = dict(zip(itemnames, itemrecs))
        else:
            self.itemrecs = [None for itnm in itemnames]
            self.itemd = dict(zip(itemnames, self.itemrecs))

    def changerow(self, delta):
        self.index = self.L(self.index + delta)

    def prevrow(self):
        self.changerow(-1)

    def nextrow(self):
        self.changerow(1)

    def on_rowChange(self, *args):
        self.rowChanged.emit(self.index)

    @property
    def index(self):
        return self.listWidget.currentRow()

    @index.setter
    def index(self, i):
        self.listWidget.setCurrentRow(int(i))

    @property
    def current_itemname(self):
        return self.listWidget.currentItem()

    @property
    def current_itemrec(self):
        return self.itemrecs[self.listWidget.currentRow()]

    @property
    def current_item(self):
        return self.listWidget.currentItem(), self.itemrecs[self.listWidget.currentRow()]

if __name__ == '__main__':
    pass
